<template>
  <div>
    <div v-if="showMergeUserModal" class="c-pf c-pz10000 c-p-t0 c-p-l0 c-p-b0 c-p-r0 c-translucent-balck60">
      <div class="c-ww540 c-m-auto c-textAlign-c c-pf c-p-t0 c-p-l0 c-p-b0 c-p-r0">
        <header v-if="mergeStep == 1" class="c-ww540 c-br20 c-bg-white c-pt40 c-pb32 c-ph40 c-fs22 c-lh36 c-textAlign-l c-p c-mb30">
          <div class="tip-area c-flex-row c-flex-center c-fs24 c-fw600">
            <img class="c-ww28 c-hh26 c-mr10" src="@/assets/bind-phone-notice.png" alt="" />
            <span>重要提醒</span>
          </div>
          <div>1.请选择一个作为主账号，<span class="c-fc-FF300B">另一账号将会被注销</span></div>
          <div>2.注销账号的余额、优惠券、课程等资产将迁移到主账号，其他数据将会丢失</div>
        </header>
        <article class="c-p c-bg-white c-br20">
          <div class="c-fs32 c-pt40 c-pb20 c-fw-b c-textAlign-c">绑定手机号</div>
          <div class="c-maxh58vh c-content-auto c-br-bl20 c-br-br20 c-p c-mt10 c-pb140">
            <div class="c-ph40 c-textAlign-l">
              <section
                v-for="(item, index) in userInfo"
                :key="index"
                @click="selectUser(index)"
                class="c-p c-mt20 c-bg-white c-br20 c-flex-column c-justify-sb c-aligni-center"
                :class="selectIndex == index ? 'theme-bd4' : 'c-bd4-EEEEEE'"
              >
                <div class="c-w100 c-flex-grow1 c-flex-row c-justify-sb c-pl30 c-pr10 c-pv20">
                  <div class="c-p c-ww72 c-hh72 c-brp50 c-flex-shrink0">
                    <div class="c-pa c-p-b0 c-p-r0 c-flex-row c-aligni-center c-pz10">
                      <div
                        style="z-index: -1"
                        v-if="checkIncludeWechat(item.fromChannel)"
                        :class="checkIncludeMobile(item.fromChannel) ? 'c-mrm16' : ''"
                        class="c-flex-shrink0 c-flex-row c-flex-center"
                      >
                        <img src="@/assets/i/wap/common/wechat-icon.png" alt="" class="c-ww30 c-hh30 c-brp50" />
                      </div>
                      <div v-if="checkIncludeMobile(item.fromChannel)" class="c-flex-shrink0 c-flex-row c-flex-center">
                        <img src="@/assets/i/wap/common/mobile-icon.png" alt="" class="c-ww30 c-hh30 c-brp50" />
                      </div>
                    </div>
                    <img class="c-ww72 c-hh72 c-brp50" :src="$addXossFilter(item.headimgurl, require('@/assets/defult_head.png'))" alt="" />
                  </div>
                  <div class="c-flex-grow1 c-pl20 c-w0 c-fw400">
                    <div class="c-fs24 c-fw600 c-fc-xblack c-text-ellipsis1 c-flex-row c-aligni-center">
                      <div class="c-text-ellipsis1">{{ item.nickname }}</div>
                      <identity-com :isShowOrdinary="false" :vipType="item.vipType"></identity-com>
                    </div>
                    <div class="c-fs20 c-fc-gray c-textAlign-l">
                      <div class="c-mt10 c-flex-row c-aligni-center">
                        <div>已购课程：{{ item.courseNum }}</div>
                        <div class="c-mh10 c-bd-l1-gray c-hh20"></div>
                        <div>优惠券：{{ item.couponNum }}</div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="c-w100 c-bg-fa c-pv12 c-br-bl20 c-br-br20 c-ph30 c-fs20 c-fc-gray">
                  <div class="c-w100 c-flex-row">
                    <div class="c-w45 c-flex-row">
                      <span class="c-flex-shrink0">余额：</span>
                      <span class="c-fc-xblack">{{ Number(item.balance || 0).toFixed(2) }}</span>
                    </div>
                    <div class="c-w55 c-flex-row">
                      <span class="c-flex-shrink0">{{ customPointName }}：</span>
                      <span class="c-fc-xblack">{{ item.points }}</span>
                    </div>
                  </div>
                  <div class="c-w100 c-flex-row c-mt10">
                    <div class="c-w45 c-flex-row">
                      <span class="c-flex-shrink0">虚拟币：</span>
                      <span class="c-fc-xblack">{{ item.coinAmount }}</span>
                    </div>
                    <div class="c-w55 c-flex-row">
                      <span class="c-flex-shrink0">手机号：</span>
                      <span class="c-fc-xblack">{{ item.mobile }}</span>
                    </div>
                  </div>
                </div>
                <!-- 账号右上角状态 -->
                <div class="conflict-user c-flex-row c-flex-center c-fc-white">{{ getCountStatusText(index) }}</div>
                <!-- 合并账号第一步才需要选择账号 -->
                <div v-if="mergeStep == 1" class="check-user c-flex-row c-flex-center" :class="selectIndex == index ? 'theme-bg' : 'c-bg-eee'">
                  <span class="iconfont c-fs16 c-fc-white">&#xe8f8;</span>
                </div>
              </section>
              <section v-if="mergeStep == 2" class="c-bg-fa c-ph30 c-pv20 c-mt20 c-br20 c-fs20">
                <div class="c-fc-xblack c-lh28">
                  <!-- 目前只会出现最多2个账号的情况 -->
                  <span>将</span>
                  <span class="c-fw600">{{destoryUserName}}</span>
                  <span>以下数据迁移到</span>
                  <span class="c-fw600">{{ userInfo[selectIndex].nickname }}</span>
                  <span class="c-fc-gray">余额、已购课程、优惠券、虚拟币、{{ customPointName }}。</span>
                </div>
                <div class="c-fc-xblack c-mt20 c-lh28">
                  <span class="c-fw600">{{ destoryUserName }}</span>
                  <span>的其他数据将永远丢失无法找回，包含但不限于：</span>
                  <span class="c-fc-gray">课程学习进度、身份、客户关系、收藏记录等</span>
                </div>
              </section>
            </div>
            <div
              class="c-br-bl20 c-br-br20 c-pf c-p-b0 c-bg-white c-w100 c-pv40 c-ph40 c-flex-row c-justify-sb c-aligni-center c-pz100 c-maxw640"
              :class="userInfo.length > 2 ? 'c-box-shadowEdu' : ''"
            >
              <div class="c-flex-row c-flex-center c-fs28 c-fc-xblack c-bd1-mgray c-ww210 c-hh60 c-br40" @click="tapExitMerge">退出合并</div>
              <div v-if="mergeStep == 1" class="c-flex-row c-flex-center c-fs28 c-fc-white theme-bg c-ww210 c-hh60 c-br40 c-ml20" @click="tapNextStep">下一步</div>
              <div v-if="mergeStep == 2" class="c-flex-row c-flex-center c-fs28 c-fc-white theme-bg c-ww210 c-hh60 c-br40 c-ml20" @click="tapConfirmMerge">确认合并</div>
            </div>
          </div>
        </article>
      </div>
    </div>
    <transition name="fade">
      <div ref="confirmModal" v-if="isShowCombine" @click.self="clickCancel" class="confirm-modal">
        <article class="c-ww540 c-bg-white c-br20 c-pt60">
          <div class="c-ph24 c-fs28 c-fw-b c-textAlign-c c-mb24">提示</div>
          <div class="c-maxh280 c-ph40 c-contexty-scroll c-fs24">确定要将{{ destoryUserName }}的数据迁移到【{{ userInfo[this.selectIndex].nickname }}】吗?</div>
          <footer class="c-mt40 c-bd-t1-f6 c-flex-row c-flex-center">
            <div @click="clickCancel" class="comfirm-modal-btn btn-cancel">取消</div>
            <div @click="clickConfirm" class="comfirm-modal-btn theme-fc">确定</div>
          </footer>
        </article>
      </div>
    </transition>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { utilJs } from '@/utils/common.js';
import identityCom from '@/components/templates/common/identityCom.vue';
export default {
  name: 'bindPhoneModal',
  components: {
    identityCom
  },
  props: {
    showBindPhoneModal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      customPointName: localStorage.getItem('customPointName'), //自定义积分名称
      mergeStep: 1,
      selectIndex: 0, // 选中的用户
      userInfo: [],
      isShowCombine: false //合并账号提示
    };
  },

  computed: {
    ...mapState({
      bindData: state => state.oem_store.bindData,
      showMergeUserModal: state => state.oem_store.showMergeUserModal,
      userInfoList: state => state.oem_store.userInfoList
    }),
    destoryUserName() {
      if (!this.userInfo) {
        return '';
      }
      let nameTextArr = [];
      for (let i = 0; i < this.userInfo.length; i++) {
        const item = this.userInfo[i];
        if (i != this.selectIndex) {
          nameTextArr.push(item.nickname);
        }
      }
      return nameTextArr.join('、');
    }
  },
  watch: {
    showMergeUserModal: {
      handler(val, oldVal) {
        val && this.init();
      },
      immediate: true
    }
  },
  methods: {
    init() {
      this.customPointName = localStorage.getItem('customPointName') || '积分';
      this._companyId = utilJs.getCompanyIdByHerf();
      this._checkTimes = 0;
      this._checkTimeCon = null;
      this.selectIndex = 0;
      this.mergeStep = 1;
      this.userInfo = utilJs.deepCopy(this.userInfoList);
    },
    selectUser(index) {
      if (this.mergeStep != 1) {
        return;
      }
      this.selectIndex = index;
    },
    getCountStatusText(index) {
      // 当前账号显示内容
      if (index == this.selectIndex) {
        return '当前账号';
      }
      let text = '';
      if (index != this.selectIndex) {
        text = '冲突账号';
      }
      if (this.mergeStep == 2) {
        text += '，即将销毁';
      }
      return text;
    },
    tapExitMerge() {
      this.$store.commit('updateShowMergeUserModal', false);
    },
    tapNextStep() {
      //合并所有账号的来源、余额、课程、积分、优惠券、虚拟币 到选择的账户上
      let totalChannel = [];
      let totalBalance = 0;
      let taotalCouponNum = 0;
      let totalCourseNum = 0;
      let totalPoints = 0;
      let totalCoinAmount = 0;
      for (let i = 0; i < this.userInfo.length; i++) {
        const item = this.userInfo[i];
        totalBalance += item.balance * 1;
        taotalCouponNum += item.couponNum * 1;
        totalCourseNum += item.courseNum * 1;
        totalPoints += item.points * 1;
        totalCoinAmount += item.coinAmount * 1;
        totalChannel = [...totalChannel, ...item.fromChannel];
        item.fromChannel = [];
        item.balance = 0;
        item.couponNum = 0;
        item.courseNum = 0;
        item.points = 0;
        item.coinAmount = 0;
        //清除销毁账号的会员身份
        if (this.selectIndex != i) {
          item.vipType = 0;
          item.vipName = '';
        }
      }
      this.userInfo[this.selectIndex] = {
        ...this.userInfo[this.selectIndex],
        ...{
          fromChannel: totalChannel,
          balance: totalBalance,
          couponNum: taotalCouponNum,
          courseNum: totalCourseNum,
          points: totalPoints,
          coinAmount: totalCoinAmount
        }
      };
      this.mergeStep = 2;
    },
    tapConfirmMerge() {
      this.isShowCombine = true;
    },
    //取消
    clickCancel() {
      this.isShowCombine = false;
    },
    //确定绑定
    clickConfirm() {
      this.isShowCombine = false;
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;
      this.$loading.show({
        text: '账号合并中，请勿关闭页面'
      });
      utilJs.postMethod(
        `${global.apiurl}members/bindMobile`,
        this.bindData,
        res => {
          localStorage.setItem('uMobile', this.bindData.mobile);
          this.bindGetIntegration();
          this.bindMobile();
          this._isLoading = false;
        },
        () => {
          this.$loading.hide();
          this._isLoading = false;
        }
      );
    },
    bindMobile() {
      const selectedUserId = this.userInfo[this.selectIndex].userId;
      const destoryUserId = this.userInfo.filter(item => item.userId != selectedUserId).map(i => i.userId);
      let data = {
        mobile: this.bindData.mobile,
        verifyCode: this.bindData.code,
        fromApp: 'qt',
        companyId: this._companyId,
        userId: selectedUserId,
        cancelUserId: destoryUserId
      };
      utilJs.postMethod(`${global.apiurl}accountConnect/accountCombine`, data, res => {
        if (res.t && res.u && res.c) {
          this.checkMergeInfo(data);
        }
      }, () => {
        this.$loading.hide();
      });
    },
    /**
     * 每隔2s检查下合并成功了没
     */
    checkMergeInfo(data) {
      this._checkTimes = 0;
      clearTimeout(this._checkTimeCon);
      this._checkTimeCon = setTimeout(() => {
        this._checkTimes += 1;
        utilJs.postMethod(`${global.apiurl}accountConnect/checkMergeInfo`, data, res => {
          if (res && res.res) {
            clearInterval(this._checkInterval);
            this._checkInterval = null;
            this._checkTimes = 0;
            this.$showCjToast({
              text: '合并成功',
              type: 'success'
            });
            this.$emit('finishBindMobile');
            this.$loading.hide();
            this.isShowCombine = false;
            this.$store.commit('updateShowMergeUserModal', false);
            this.$store.commit('updateShowBindPhoneModal', {
              showBindPhoneModal: false
            });
            return;
          }
          if (this._checkTimes > 10) {
            // 20秒内没有合并成功就要退出了
            clearInterval(this._checkInterval);
            this._checkInterval = null;
            this._checkTimes = 0;
            this.$loading.hide();
            this.$showCjToast({
              text: '因用户数据量大，账号还在合并中，请耐心等待...',
              type: 'success'
            });
            this.$emit('finishBindMobile');
            this.$store.commit('updateShowMergeUserModal', false);
            this.$store.commit('updateShowBindPhoneModal', {
              showBindPhoneModal: false
            });
            return;
          }
          this.checkMergeInfo(data);
        }, () => {
          this.$loading.hide();
        });
      }, 2000);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.destroy-icon {
  background: rgba(244, 98, 98, 0.1);
  border-radius: 4px;
  color: #f46262;
}

.boxShadow {
  box-shadow: 0px -10px 20px -12px rgba(0, 0, 0, 0.1);
}

.c-fc-FF300B {
  color: #ff300b;
}
.tip-area {
  width: 4.75rem;
  height: 1.35rem;
  background: #fff1e5;
  border-radius: 0.6rem 0.6rem 0.6rem 0;
  position: absolute;
  left: 0;
  top: -0.7rem;
}
.c-bd4-EEEEEE {
  border: 0.1rem solid #eeeeee;
}
.current-user {
  padding-left: 0.3rem;
  padding-right: 0.3rem;
  height: 0.7rem;
  border-radius: 0.5rem 0.5rem 0 0.5rem;
  font-size: 0.45rem;
  position: absolute;
  top: -0.1rem;
  right: -0.1rem;
}
.conflict-user {
  padding-left: 0.3rem;
  padding-right: 0.3rem;
  height: 0.7rem;
  background: #ff5355;
  border-radius: 0.5rem 0.5rem 0 0.5rem;
  font-size: 0.45rem;
  position: absolute;
  top: -0.1rem;
  right: -0.1rem;
}
.check-user {
  width: 1rem;
  height: 1rem;
  /* background: #EEEEEE; */
  border-radius: 0.5rem 0 0.5rem 0;
  position: absolute;
  bottom: -0.1rem;
  right: -0.1rem;
}
.c-maxh58vh {
  max-height: 58vh;
}

/* 弹窗 */
.confirm-modal {
  position: fixed;
  z-index: 200000;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.comfirm-modal-btn {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 0;
  height: 1.85rem;
  font-size: 0.7rem;
}
.btn-cancel {
  color: #666;
  border-right: 1px solid #f6f6f6;
}
</style>
